<script lang="ts" setup>
import {computed, onMounted, ref} from 'vue'
import {useForm} from '@inertiajs/vue3'
import {FormInstance, Message} from '@arco-design/web-vue'
import {route} from "ziggy-js"
import AuthLayout from "./Layout.vue";

const captchaSrc = ref(`/captcha/math?t=${Math.random()}`)
const step = ref(1) // 1: 验证身份, 2: 重置密码
const countdown = ref(0)

// 注册状态
const isLoading = ref(false)
const isSending = ref(false)
// 表单实例
const FormRef = ref<FormInstance>(null);
const form = useForm({
    phone: '',
    captcha: '',
    sms_code: '',
    password: '',
    confirm_password: '',
})

// 表单验证规则
const rules = computed(() => {
    if (step.value === 1) {
        return {
            phone: [
                { required: true, message: '请输入手机号', trigger: 'blur' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
            ],
            captcha: [
                { required: true, message: '请输入图形验证码', trigger: 'blur' }
            ],
            sms_code: [
                { required: true, message: '请输入短信验证码', trigger: 'blur' },
                { len: 6, message: '验证码应为6位数字', trigger: 'blur' }
            ]
        }
    } else {
        return {
            password: [
                { required: true, message: '请输入新密码', trigger: 'blur' },
                { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
            ],
            confirm_password: [
                { required: true, message: '请输入确认密码', trigger: 'blur' },
                {
                    validator: (value: string, callback: any) => {
                        if (value !== form.password) {
                            callback('两次输入密码不一致')
                        }
                    },
                    trigger: 'blur'
                }
            ]
        }
    }
})

// 刷新验证码
const refreshCaptcha = () => {
    captchaSrc.value = `/captcha/math?t=${Math.random()}`;
};

// 发送短信验证码
const sendSmsCode = async () => {
    // 先验证手机号和图形验证码
    try {
        await FormRef.value?.validate(['phone', 'captcha'])
    } catch (error) {
        Message.error('请先填写正确的手机号和图形验证码')
        return
    }

    isSending.value = true
    // 模拟发送短信验证码
    setTimeout(() => {
        isSending.value = false
        countdown.value = 60
        Message.success('验证码已发送')

        // 开始倒计时
        const timer = setInterval(() => {
            countdown.value--
            if (countdown.value <= 0) {
                clearInterval(timer)
            }
        }, 1000)
    }, 1000)
}

// 下一步 - 验证身份
const nextStep = async () => {
    try {
        await FormRef.value?.validate()
        // 模拟验证成功
        step.value = 2
        Message.success('身份验证成功')
    } catch (error) {
        Message.error('请检查填写的信息')
    }
}

// 提交重置密码
const submitReset = async () => {
    try {
        await FormRef.value?.validate()

        isLoading.value = true
        form.post(route('password.update'), {
            onSuccess: () => {
                Message.success('密码重置成功，请使用新密码登录')
                // 这里可以跳转到登录页
            },
            onError: (errors) => {
                Message.error('重置失败，请稍后重试')
                const fields = {} as any;
                for (const [fieldName, messages] of Object.entries(errors)) {
                    fields[fieldName] = {
                        status: 'error',
                        message: messages
                    };
                }
                FormRef.value.setFields(fields);
            },
            onFinish: () => {
                isLoading.value = false;
            }
        })
    } catch (error) {
        // 验证失败
    }
}

// 返回上一步
const prevStep = () => {
    step.value = 1
}

onMounted(() => {
    refreshCaptcha();
})
</script>

<template>
    <auth-layout>
        <div class="forgot-password-section">
            <div class="header">
                <h2>找回密码</h2>
                <p>请按照以下步骤重置您的账户密码</p>

                <!-- 步骤指示器 -->
                <div class="steps">
                    <div :class="{ active: step === 1, completed: step > 1 }" class="step">
                        <div class="step-number">1</div>
                        <div class="step-label">验证身份</div>
                    </div>
                    <div class="step-line"></div>
                    <div :class="{ active: step === 2 }" class="step">
                        <div class="step-number">2</div>
                        <div class="step-label">重置密码</div>
                    </div>
                </div>
            </div>

            <!-- 第一步：验证身份 -->
            <a-form
                v-if="step === 1"
                ref="FormRef"
                :model="form"
                :rules="rules"
                class="forgot-password-form"
                layout="vertical"
                size="large"
            >
                <a-form-item
                    :hide-label="true"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    field="phone"
                    label="手机号"
                >
                    <a-input
                        v-model="form.phone"
                        allow-clear
                        autocomplete="off"
                        class="input-field"
                        placeholder="请输入您注册时使用的手机号"
                    >
                        <template #prefix>
                            <icon-mobile />
                        </template>
                    </a-input>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    field="captcha"
                    label="图形验证码"
                >
                    <div class="captcha-group">
                        <a-input
                            v-model="form.captcha"
                            allow-clear
                            autocomplete="off"
                            class="input-field"
                            placeholder="请输入右侧验证码"
                        >
                            <template #prefix>
                                <icon-safe />
                            </template>
                        </a-input>

                        <div class="captcha-image" title="点击刷新验证码" @click="refreshCaptcha">
                            <img v-if="captchaSrc" :src="captchaSrc" alt="验证码" />
                        </div>
                    </div>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    field="sms_code"
                    label="短信验证码"
                >
                    <div class="sms-code-group">
                        <a-input
                            v-model="form.sms_code"
                            allow-clear
                            autocomplete="off"
                            class="input-field"
                            maxlength="6"
                            placeholder="请输入6位短信验证码"
                        >
                            <template #prefix>
                                <icon-message />
                            </template>
                        </a-input>

                        <a-button
                            :disabled="isSending || countdown > 0"
                            class="sms-button"
                            @click="sendSmsCode"
                        >
                            {{ countdown > 0 ? `${countdown}秒后重发` : (isSending ? '发送中...' : '获取验证码') }}
                        </a-button>
                    </div>
                </a-form-item>

                <a-form-item :hide-label="true">
                    <a-button
                        class="next-button"
                        html-type="button"
                        long
                        size="large"
                        type="primary"
                        @click="nextStep"
                    >
                        下一步
                    </a-button>
                </a-form-item>
            </a-form>

            <!-- 第二步：重置密码 -->
            <a-form
                v-else
                ref="FormRef"
                :model="form"
                :rules="rules"
                class="forgot-password-form"
                layout="vertical"
                size="large"
                @submit="submitReset"
            >
                <div class="success-tip">
                    <icon-check-circle style="color: #00B42A; margin-right: 8px;" />
                    身份验证成功，请设置您的新密码
                </div>

                <a-form-item
                    :hide-label="true"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    field="password"
                    label="新密码"
                >
                    <a-input-password
                        v-model="form.password"
                        allow-clear
                        autocomplete="new-password"
                        class="input-field"
                        placeholder="请设置您的新密码"
                    >
                        <template #prefix>
                            <icon-lock />
                        </template>
                    </a-input-password>
                    <template #extra>
                        <div class="password-tip">密码长度至少6位，建议包含字母和数字</div>
                    </template>
                </a-form-item>

                <a-form-item
                    :hide-label="true"
                    :label-col-props="{ span: 24 }"
                    :wrapper-col-props="{ span: 24 }"
                    field="confirm_password"
                    label="确认新密码"
                >
                    <a-input-password
                        v-model="form.confirm_password"
                        allow-clear
                        autocomplete="new-password"
                        class="input-field"
                        placeholder="请再次输入新密码"
                    >
                        <template #prefix>
                            <icon-lock />
                        </template>
                    </a-input-password>
                </a-form-item>

                <a-form-item :hide-label="true">
                    <div class="action-buttons">
                        <a-button
                            class="back-button"
                            html-type="button"
                            size="large"
                            @click="prevStep"
                        >
                            上一步
                        </a-button>
                        <a-button
                            :disabled="isLoading"
                            :loading="isLoading"
                            class="reset-button"
                            html-type="submit"
                            long
                            size="large"
                            type="primary"
                        >
                            {{ isLoading ? '重置中...' : '立即重置' }}
                        </a-button>
                    </div>
                </a-form-item>
            </a-form>

            <div class="login-link">
                <a-link :hoverable="false" :href="route('login')">
                    <icon-left style="margin-right: 4px;" />
                    返回登录
                </a-link>
            </div>
        </div>
    </auth-layout>
</template>

<style lang="scss" scoped>
.forgot-password-section {
    display: flex;
    flex-direction: column;
    justify-content: center;
    width: 100%;
    max-width: 420px;
    margin: 0 auto;
}

.header {
    margin-bottom: 40px;
    text-align: center;
}

.header h2 {
    font-size: 28px;
    font-weight: 700;
    color: #1a1a1a;
    margin-bottom: 10px;
}

.header p {
    color: #666;
    font-size: 16px;
    margin-bottom: 30px;
}

/* 步骤指示器 */
.steps {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto;
    max-width: 300px;
}

.step {
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
}

.step-number {
    width: 32px;
    height: 32px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f0f0f0;
    color: #999;
    font-weight: 600;
    margin-bottom: 8px;
    transition: all 0.3s ease;
}

.step.active .step-number {
    background: linear-gradient(135deg, #165DFF, #722ED1);
    color: white;
    box-shadow: 0 4px 10px rgba(22, 93, 255, 0.3);
}

.step.completed .step-number {
    background: #00B42A;
    color: white;
}

.step-label {
    font-size: 14px;
    color: #999;
    transition: all 0.3s ease;
}

.step.active .step-label {
    color: #165DFF;
    font-weight: 500;
}

.step-line {
    width: 80px;
    height: 2px;
    background: #f0f0f0;
    margin: 0 10px;
    position: relative;
    top: -16px;
}

.forgot-password-form {
    width: 100%;
}

.input-field {
    border-radius: 10px;
    transition: all 0.3s ease;

    &:focus-within {
        box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
    }
}

.password-tip {
    font-size: 12px;
    color: #999;
    margin-top: 4px;
}

.captcha-group {
    width: 100%;
    display: flex;
    gap: 12px;
    align-items: flex-start;
}

.captcha-image {
    width: 120px;
    height: 34px;
    border-radius: 8px;
    cursor: pointer;
    overflow: hidden;
    flex-shrink: 0;
    position: relative;
    transition: all 0.3s ease;
}

.captcha-image img {
    height: 100%;
    width: auto;
}

.sms-code-group {
    width: 100%;
    display: flex;
    gap: 12px;
    align-items: flex-start;
}

.sms-button {
    width: 120px;
    white-space: nowrap;
    flex-shrink: 0;
    border-radius: 8px;
    height: 34px;
}

.success-tip {
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f6ffed;
    border: 1px solid #b7eb8f;
    border-radius: 8px;
    padding: 12px 16px;
    margin-bottom: 24px;
    color: #389e0d;
    font-size: 14px;
}

.action-buttons {
    width: 100%;
    display: flex;
    gap: 12px;
}

.back-button {
    flex: 1;
    height: 42px;
    border-radius: 10px;
}

.next-button, .reset-button {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #165DFF, #722ED1);
    color: white;
    border: none;
    border-radius: 10px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    height: 42px;
    margin-bottom: 20px;
    box-shadow: 0 4px 10px rgba(22, 93, 255, 0.3);

    &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 6px 15px rgba(22, 93, 255, 0.4);
    }

    &:active {
        transform: translateY(0);
    }
}

.login-link {
    text-align: center;
    margin-top: 20px;
    color: #666;
    font-size: 15px;
}

.login-link a {
    color: #165DFF;
    text-decoration: none;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
}

/* 响应式设计 */
@media (max-width: 576px) {
    .forgot-password-section {
        padding: 0 16px;
    }

    .captcha-group, .sms-code-group {
        flex-direction: column;
    }

    .captcha-image, .sms-button {
        width: 100%;
        height: 45px;
    }

    .header h2 {
        font-size: 24px;
    }

    .steps {
        max-width: 250px;
    }

    .step-line {
        width: 60px;
    }

    .action-buttons {
        flex-direction: column;
    }
}

/* Arco Design 组件样式微调 */
:deep(.arco-form-item-label) {
    font-weight: 500;
    margin-bottom: 8px;
}

:deep(.arco-form-item-extra) {
    margin-top: 4px;
}
</style>
